import { MouseEventHandler, useMemo, useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Button, message } from 'antd';
import { useInbizRouter } from '@inbiz/hooks';
import { useApp } from '@inbiz/render';
import { processRelease, saveOrUpdateProcessDesign } from '../server';
import { versionManagement as version } from '../operations';
import ProcessIcon from '../ProcessIcon';
import variableSettings from '../../assets/images/variableSettings';
import versionManagement from '../../assets/images/versionManagement';
import './style.less';

const Header = forwardRef((props: any, ref) => {
  const { processData, customPropertiesPanelRef, bpmnXML, customModeler, setVariableDrawerVisiable, setVersionVisiable } = props;
  const [publishLoading, setPublishLoading] = useState(false);
  const [saveLoading, setSaveLoading] = useState(false);
  const history = useInbizRouter();
  const appInfo = useApp();

  const doRelease = async () => {
    setPublishLoading(true);
    try {
      let result = await processRelease(processData?.processKey, 'key');
      if (result?.code == '200') {
        message.success(result?.message);
      } else {
        message.error(result?.message);
      }
      setPublishLoading(false);
    } catch (error: any) {
      message.error(error)
      setPublishLoading(false);
    }
  };

  const getReleaseParams = () => {
    const __processData = processData || { processKey: '' };
    return __processData?.processKey;
  };

  const doSave = async (callback: Function, success: Function) => {
    const _customModeler = customModeler || window?.inbizBpmn || {};
    const _processData = processData ||  {};
    const ElementRegistry = _customModeler.get('elementRegistry');
    const allElementIds = ElementRegistry.getAll()?.map((item: { id: string; }) => item?.id);
    let _userTaskData = customPropertiesPanelRef?.current?.userTaskData?.filter((item: { activityId: string; }) => allElementIds?.includes(item?.activityId));
    let _callActivityTask = customPropertiesPanelRef?.current?.subProcessData?.filter((item: { activityId: string; }) => allElementIds?.includes(item?.activityId));
    let _sequenceFlow = customPropertiesPanelRef?.current?.sequenceFlowData?.filter((item: { activityId: string; }) => allElementIds?.includes(item?.activityId));
    // let _id = '';
    // let _name = '';
    // let _identityid = '';
    // let _memberarea = '';
    _userTaskData = _userTaskData?.map((item: { activityId: string; baseInfo: any; }) => {
      const isCounterSignNode = item?.baseInfo?.hasOwnProperty('isSequential');
      // if (item?.activityId == firstTaskId) {
      //   let _assignee = item?.baseInfo?.assignee;
      //   _id = _assignee?.map((item1: any) => item1?.id)?.join(',');
      //   _name = _assignee?.map((item1: any) => item1?.name)?.join(',');
      //   _identityid = _assignee?.map((item1: any) => item1?.identityid)?.join(',');
      //   _memberarea = _assignee?.map((item1: any) => item1?.memberarea)?.join(',');
      // }
      return {
        ...item,
        baseInfo: {
          ...item?.baseInfo,
          isCounterSignNode,
        },
      };
    });
    let _extPropJson = {
      processDefinition: customPropertiesPanelRef?.current?.processDefinition,
      userTask: _userTaskData,
      callActivityTask: _callActivityTask,
      sequenceFlow: _sequenceFlow,
    };
    const result = await saveOrUpdateProcessDesign({
      ..._processData,
      proLcon: customPropertiesPanelRef?.current?.processDefinition?.proLcon,
      groupId: customPropertiesPanelRef?.current?.processDefinition?.groupId,
      // identityId: _identityid,
      // potentialStartName: _name,
      // potentialStarterId: _id,
      // potentialType: _memberarea,
      sort: _processData?.sort || 5,
      pageKey: _processData?.pageKey || 1,
      pcPageKey: _processData?.pcPageKey || '',
      extPropJson: JSON.stringify(_extPropJson),
      processDefinitionXml: _bpmnXML,
      name: _extPropJson?.processDefinition?.processName,
    });
    if (result?.code == '200') {
      message.success(result?.message);
      success && success();
    } else {
      message.error(result?.message);
    }
    callback && callback();
  }

  const getSaveParams = () => {
    const _customModeler = customModeler || window?.inbizBpmn || {};
    const _processData = processData || {};
    const _bpmnXML = window['processXml'];
    const ElementRegistry = _customModeler.get('elementRegistry');
    const allElementIds = ElementRegistry.getAll()?.map((item: { id: string; }) => item?.id);
    let _userTaskData = customPropertiesPanelRef?.current?.userTaskData?.filter((item: { activityId: string; }) => allElementIds?.includes(item?.activityId));
    let _callActivityTask = customPropertiesPanelRef?.current?.subProcessData?.filter((item: { activityId: string; }) => allElementIds?.includes(item?.activityId));
    let _sequenceFlow = customPropertiesPanelRef?.current?.sequenceFlowData?.filter((item: { activityId: string; }) => allElementIds?.includes(item?.activityId));
    let fieldPerm: any[] = [];
    _userTaskData = _userTaskData?.map((item: any) => {
      const isCounterSignNode = item?.baseInfo?.hasOwnProperty('isSequential');
      if (item?.assembly && item?.assembly?.length > 0) {
        const itemFieldPerm = {
          activityId: item?.activityId,
          fields: item?.assembly,
        };
        fieldPerm?.push(itemFieldPerm);
      };
      if (item?.hasOwnProperty('assembly')) {
        delete item.assembly;
      };
      return {
        ...item,
        baseInfo: {
          ...item?.baseInfo,
          isCounterSignNode,
        },
      };
    });

    let _extPropJson = {
      processDefinition: customPropertiesPanelRef?.current?.processDefinition,
      userTask: _userTaskData,
      callActivityTask: _callActivityTask,
      sequenceFlow: _sequenceFlow,
    };

    const params = {
      ..._processData,
      proLcon: customPropertiesPanelRef?.current?.processDefinition?.proLcon,
      groupId: customPropertiesPanelRef?.current?.processDefinition?.groupId,
      // identityId: _identityid,
      // potentialStartName: _name,
      // potentialStarterId: _id,
      // potentialType: _memberarea,
      sort: _processData?.sort ?? 5,
      pageKey: _processData?.pageKey ?? 1,
      pcPageKey: _processData?.pcPageKey ?? '',
      name: _extPropJson?.processDefinition?.processName,
      extPropJson: JSON.stringify(_extPropJson),
      processDefinitionXml: _bpmnXML,
      fieldPerm,
    };
    return params;
  };

  const openVariable = () => {
    setVariableDrawerVisiable(true);
  };

  const openVer = () => {
    setVersionVisiable(true);
  };

  const icons = useMemo(() => {
    return [
      {
        key: 'variableSettings',
        component: variableSettings,
        title: '设置变量',
        onClick: openVariable,
      },
      {
        key: 'versionManagement',
        component: versionManagement,
        title: '版本管理',
        onClick: openVer,
      }
    ]
  }, [processData, appInfo]);

  const butttons = useMemo(() => {
    return [
      {
        key: 'save',
        text: '保存',
        type: 'default',
        loading: saveLoading,
        onClick: doSave,
      },
      {
        key: 'publish',
        text: '发布',
        type: 'primary',
        loading: publishLoading,
        onClick: doRelease,
      }
    ]
  }, [doRelease, processData, publishLoading, customPropertiesPanelRef, bpmnXML]);

  const headerLeft = (
    <div className="process-designer-header-left">
      <div className="process-designer-header-left-icon">
        <ProcessIcon
          processIconInfo={processData?.proLcon ? processData?.proLcon?.trim() : 'font_family'}
          style={{ fontSize: 16 }}
          imgStyle={{ width: 16, height: 16 }}
        />
      </div>
      <div className='process-designer-header-left-line'></div>
      <div>{processData?.name || '流程名称'}</div>
    </div>
  );

  const headerRight = (
    <div className="process-designer-header-right">
      {
        icons?.map((item: { key: string, title: string, component: any, onClick: MouseEventHandler<HTMLSpanElement> }) => {
          return (
            <span
              key={item?.key}
              className='process-designer-header-right-icon'
              onClick={(e) => {
                if (!customModeler) {
                  return;
                };
                item?.onClick(e)
              }}
              title={item?.title}
            >
              <item.component />
            </span>
          )
        })
      }
      {
        butttons?.map((item2: { key: string, text: string, type: any, onClick: any, loading: boolean }) => {
          return <Button
            key={item2?.key}
            type={item2?.type}
            disabled={history?.location?.query?.view == 'true'}
            loading={item2?.loading}
            onClick={() => {
              if (!customModeler) {
                return;
              };
              item2?.onClick()
            }}
          >
            {item2?.text}
          </Button>
        })
      }
    </div>
  );

  useImperativeHandle(ref, () => ({
    getReleaseParams,
    getSaveParams,
    doRelease,
    doSave,
    openVer,
  }), [customModeler]);

  return (
    <div className="process-designer-header" style={{ display: history?.location?.query?.id ? 'flex' : 'none' }}>
      {headerLeft}
      {headerRight}
    </div>
  );
});

export default Header;